package com.beerandjesus.sportofkings.handicapper;

import com.beerandjesus.sportofkings.handicapper.app.CardAnalyzer;
import com.beerandjesus.sportofkings.handicapper.app.CardAnalyzerException;
import com.beerandjesus.sportofkings.handicapper.dao.DAOException;
import com.beerandjesus.sportofkings.handicapper.factory.ResultsTableFactory;
import com.beerandjesus.sportofkings.handicapper.model.RaceAnalysisResultVO;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.CardVOImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * Main class for -jar execution.
 */
public class Main {
    private ApplicationContext context;
    private String filePath;

    private static final String[] CONTEXTS = new String[]{"spring-config.xml",
            "applicationContext-handicapper-jar.xml"};

    public static void main(String[] args) throws DAOException {
        if (args == null || args.length != 1) {
            printUsage();
            return;
        }
        String arg1 = args[0];
        ApplicationContext context = new ClassPathXmlApplicationContext(CONTEXTS);
        Main main = new Main();
        main.setApplicationContext(context);
        main.setFilePath(arg1);
        main.execute();
    }

    private static void printUsage() {
        System.out.println("Usage: java -jar <jarfile> [<path to past performances file>]");
    }

    public void execute() {
        CardAnalyzer cardAnalyzer = (CardAnalyzer) context.getBean("cardAnalyzer");
        ResultsTableFactory resultsTableFactory = (ResultsTableFactory) context.getBean("resultsTableFactory");
        CardVOImpl card = new CardVOImpl();
        card.setFilePath(getFilePath());
        List<RaceAnalysisResultVO> races;
        try {
            races = cardAnalyzer.analyzeCard(card);
        } catch (CardAnalyzerException e) {
            e.printStackTrace();
            return;
        }
        System.out.print(resultsTableFactory.getOutputSimpleFormat(races));

    }

    public void setApplicationContext(ApplicationContext context) {
        this.context = context;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
}
